<script setup lang="ts">
  import { onMounted, ref, watch } from 'vue';
  import { userLogin, sendMails, userRegister, sendSms, sendMailsParams, checkSmsCode } from '/@/apis/userApi';
  import { useRequest } from 'vue-request';
  import { useRoute, useRouter } from 'vue-router';
  import { i18nTranslate, LANG_CONFIG, setLang } from '/@/i18n';
  import { NotifyWarn, NotifySuccess, isNull, Encrypt, pwdReg, isEmail } from '/@/utils';
  import { Md5 } from 'ts-md5';
  // import { useTheme, useToken,useUserInfoStorage } from '/@/hooks';
  const { query } = useRoute();
  // const { updateUserInfo  } = useUserInfoStorage();
  // const { setToken } = useToken();
  const registerType = ref('MAIL');
  const router = useRouter();
  const isArgee = ref(false);
  const formData = ref({
    phone: '',
    mail: '',
    password: '',
    code: '',
    confirmPassword: '',
    welCode: query.inviteCode as string,
    areaCode: '1',
  });
  const MAX_COUNTDOWN_TIME = 60 * 1000; // ms
  // 邮箱倒计时时间，大于0时就会触发
  const countDownTime = ref(0);
  // 倒计时结束，将变量归零 ,邮箱倒计时
  const onTimeEnd = () => (countDownTime.value = 0);
  // 提交
  const onSubmit = async () => {
    if (isNull(formData.value.phone) && registerType.value === 'PHONE') {
      NotifyWarn(i18nTranslate('PleaseenterPhonenumber'));
    } else if (isNull(formData.value.mail) && registerType.value === 'MAIL') {
      NotifyWarn(i18nTranslate('PleaseenteryourEmail'));
    } else if (isNull(formData.value.mail) && registerType.value === 'ACCOUNT') {
      NotifyWarn(i18nTranslate('Pleaseenteryouraccount'));
    } else if (isNull(formData.value.code) && registerType.value === 'MAIL') {
      NotifyWarn(i18nTranslate('PleaseenteryourVerificationCode'));
    } else if (isNull(formData.value.password)) {
      NotifyWarn(i18nTranslate('Pleaseenteryourpassword'));
    } else if (!pwdReg(formData.value.password)) {
      NotifyWarn(i18nTranslate('Pleaseentera612digiatpassword'));
    } else if (formData.value.password != formData.value.confirmPassword) {
      NotifyWarn(i18nTranslate('samePasswords'));
    } else if (isNull(formData.value.welCode) || formData.value.welCode === undefined) {
      NotifyWarn(i18nTranslate('PleaseenteryourInvitationcode'));
    } else {
        if( registerType.value === 'MAIL' ) {
            const checkParams = {
            phMail: formData.value.mail,
            code:  formData.value.code ,
            type: 'REGISTER',
        };
        requestCheckSmsCode.run(checkParams);
      } else {
          const registerParams = {
          regType: registerType.value,
          phone: formData.value.phone,
          mail: formData.value.mail,
          code: registerType.value === 'MAIL' ? formData.value.code : '',
          password: Md5.hashStr(formData.value.password),
          areaCode: registerType.value === 'PHONE' ? formData.value.areaCode : '',
          welCode: formData.value.welCode,
        };
          requestUserRegister.run(registerParams);
      }
     
     
    }
  };
  // 注册
  const requestUserRegister = useRequest(userRegister, {
    manual: true,
    onSuccess() {
      NotifySuccess(i18nTranslate('registSuccessful'));
      router.push('/login');
    },
    onError() {
      return;
    },
  });

  // 发送手机验证码
  const requestSendSmsCode = useRequest(sendSms, {
    manual: true,
    onSuccess() {
      countDownTime.value = MAX_COUNTDOWN_TIME;
    },
    onError() {
      return;
    },
  });
  // 发送邮箱验证码
  const requestSendEmailCode = useRequest(sendMails, {
    manual: true,
    onSuccess() {
      countDownTime.value = MAX_COUNTDOWN_TIME;
    },
    onError() {
      return;
    },
  });
  // 点击发送按钮触发发送请求，以及倒计时
  const onRequestSend = async () => {
    if (registerType.value === 'PHONE') {
      if (isNull(formData.value.phone)) {
        NotifyWarn(i18nTranslate('Phonenumber'));
        return;
      }
      const smsCodeParams = {
        phone: formData.value.phone,
        phoneCode: formData.value.areaCode,
        type: 'REGISTER',
      };
      requestSendSmsCode.run(smsCodeParams);
    } else {
      if (!isEmail(formData.value.mail)) {
        NotifyWarn(i18nTranslate('Pleaseentertheorrectemailaddress'));
        return;
      }
      const params: sendMailsParams = {
        mailbox: formData.value.mail,
        type: 'REGISTER',
      };
      requestSendEmailCode.run(params);
    }
  };
  const onBack = () => {
    router.push('/login');
  };
  // 验证验证码是否正确
  const requestCheckSmsCode = useRequest(checkSmsCode, {
    manual: true,
    onSuccess() {
      const registerParams = {
          regType: registerType.value,
          phone: formData.value.phone,
          mail: formData.value.mail,
          code: registerType.value === 'MAIL' ? formData.value.code : '',
          password: Md5.hashStr(formData.value.password),
          areaCode: registerType.value === 'PHONE' ? formData.value.areaCode : '',
          welCode: formData.value.welCode,
        };
          requestUserRegister.run(registerParams);
    },
    onError() {
      return;
    },
  });
  // 切换方式，数据清空
  watch(registerType, () => {
    formData.value.phone = '';
    formData.value.mail = '';
    formData.value.code = '';
    formData.value.password = '';
    formData.value.confirmPassword = '';
    formData.value.welCode = '';
    countDownTime.value = 0;
  });
  const onChangeCode = (code: string) => (formData.value.areaCode = code);
</script>
<template>
  <div class="register">
    <div class="register-top flex-between">
      <div>
        <div class="close_box" @click="onBack">
          <img :src="$img('close.png')" />
        </div>
        <p class="register_title">{{ $t('Register') }}</p>
      </div>
      <div class="img_box">
        <img :src="$img('me/login-bg.png')" />
      </div>
    </div>
    <div class="register_method">
      <!-- <div
        class="method"
        @click="registerType = 'PHONE'"
        :class="registerType === 'PHONE' ? 'active' : ''"
      >
        {{ $t('Phone') }}
        <div class="line">
          <img :src="$img('me/line.png')" />
        </div>
      </div> -->
      <div
        class="method"
        @click="registerType = 'MAIL'"
        :class="registerType === 'MAIL' ? 'active' : ''"
      >
        {{ $t('Email') }}
        <div class="line">
          <img :src="$img('me/line.png')" />
        </div>
      </div>
      <div
        class="method"
        @click="registerType = 'ACCOUNT'"
        :class="registerType === 'ACCOUNT' ? 'active' : ''"
      >
        {{ $t('Account') }}
        <div class="line">
          <img :src="$img('me/line.png')" />
        </div>
      </div>
    </div>
    <div class="register_form">
      <VarForm>
        <div v-if="registerType === 'PHONE'">
          <InputPhoneNumber
            :label="$t('Phonenumber')"
            v-model="formData.phone"
            :areacode="formData.areaCode"
            @change="onChangeCode"
            :placeholder="$t('PleaseenterPhonenumber')"
          />
          <!-- <InputVerification
            :label="$t('VerificationCode')"
            v-model="formData.code"
            :loading="requestSendSmsCode.loading.value"
            @send="onRequestSend"
            :time="countDownTime"
            @end="onTimeEnd"
          /> -->
        </div>
        <div v-if="registerType === 'MAIL'">
          <InputEmail
            :label="$t('Email')"
            ref="formInputEmail"
            v-model="formData.mail"
            :placeholder="$t('PleaseenteryourEmail')"
          />
          <InputVerification
            :label="$t('VerificationCode')"
            v-model="formData.code"
            :loading="requestSendEmailCode.loading.value"
            @send="onRequestSend"
            :time="countDownTime"
            @end="onTimeEnd"
          />
        </div>
        <InputBase
          v-if="registerType === 'ACCOUNT'"
          :label="$t('Account')"
          v-model="formData.mail"
          :placeholder="$t('Pleaseenteryouraccount')"
        />
        <InputPassword
          :label="$t('Password')"
          v-model="formData.password"
          :placeholder="$t('Pleaseenteryourpassword')"
        />
        <InputPassword
          :label="$t('Confirmpassword')"
          v-model="formData.confirmPassword"
          :placeholder="$t('PleaseenteryourConfirmpassword')"
        />
        <InputBase
          :label="$t('Invitationcode')"
          v-model="formData.welCode"
          :placeholder="$t('PleaseenteryourInvitationcode')"
        />
      </VarForm>
      <!-- <div class="argee_box">
        <van-checkbox v-model="isArgee">
          <p>
            {{ $t('Readandunderstood') }}<span class="privacy" @click="$router.push('/privacy')"> {{ $t('Privacy')
              }}</span>
          </p>
        </van-checkbox>
      </div> -->
      <LargePrimaryButton block class="submit_button" @click="onSubmit">{{
        $t('Confirm')
      }}</LargePrimaryButton>
      <p class="register_text">
        {{ $t('Haveanaccount')
        }}<span class="privacy" @click="$router.push('/login')"> {{ $t('Signin') }}</span>
      </p>
    </div>
  </div>
</template>
<style lang="scss" scoped>
  .register {
    padding: 20px 30px 40px;
    .register-top {
      .img_box {
        width: 410px;
        height: 281px;
      }
    }
    .register_method {
      display: flex;
      margin-bottom: 36px;
      .method {
        color: rgba(255,255,255,0.85);
        margin-right: 64px;
        position: relative;
        text-align: center;
        min-width: 90px;
        display: flex;
        flex-direction: column;
        align-items: center;
        .line {
          margin-top: 10px;
          width: 90px;
          display: none;
        }
        &.active {
          font-size: 32px;
          font-weight: 600;
          .line {
            display: block;
          }
        }
      }
    }
    .close_box {
      width: 31px;
      height: 31px;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .register_title {
      color: #FFFFFF;
      font-size: 48px;
      font-weight: 700;
      padding: 60px 0 40px;
    }

    .register_form {
      .register_form_title {
        color: rgba(255,255,255,0.85);
        font-size: 32px;
        margin-bottom: 18px;
      }
      .argee_box {
        margin-top: 70px;
        margin-bottom: 24px;
        font-size: 26px;
        color: #161827;

        .privacy {
          color: #2f73ff;
          padding-left: 10px;
          text-decoration-line: underline;
        }
      }

      .register_text {
        margin-top: 22px;
        font-size: 26px;
        color: rgba(255,255,255,0.65);
        .privacy {
          color: #2f73ff;
          padding-left: 6px;
        }
      }
    }
  }
</style>
<style lang="scss">
  .register {
    .van-checkbox__icon {
      font-size: 24px;
    }
    .hl-input-box {
      padding-bottom: 25px;
    }
  }
</style>
